package com.example.thirdhomework

import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.thirdhomework.databinding.ActivityForthBinding

class ForthActivity : AppCompatActivity() {

    var seconds = 0
    var running = false
    var wasRunning = false

    private val binding by lazy { ActivityForthBinding.inflate((layoutInflater)) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)

        Log.d("Lifecycle","OnCreate")

        if(savedInstanceState!= null){
            seconds = savedInstanceState.getInt("seconds")
            running = savedInstanceState.getBoolean("running")
            wasRunning = savedInstanceState.getBoolean("wasRunning")
        }

        runTimer()

        binding.buttonstart.setOnClickListener {
            running = true
        }
        binding.buttonstop.setOnClickListener {
            running = false
        }
        binding.buttonrestart.setOnClickListener {
            running = true
            seconds = 0
        }
    }

   fun runTimer() {
       val handler = Handler()
       val runnable = object: Runnable{
           override fun run(){
               val hours = seconds / 3600
               val minutes = (seconds % 3600) / 60
               val secs = (seconds % 3600) % 60
               binding.textView.text = String.format("%02d:%02d:%02d", hours, minutes, secs)
               if(running){
                   seconds++
               }
               handler.postDelayed(this,1000)
           }
       }
       handler.post(runnable)
   }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)

        Log.d("Lifecycle", "OnSaveInstanceState")

        outState.putInt("seconds", seconds)
        outState.putBoolean("running", running)
        outState.putBoolean("wasRunning", wasRunning)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("Lifecycle", "OnDestroy")
    }

   override fun onStart(){
       super.onStart()
       Log.d("Lifecycle", "OnStart")
   }

    override  fun onStop() {
        super.onStop()
        Log.d("Lifecycle", "OnStop")
    }

    override fun onResume() {
        super.onResume()
        Log.d("Lifecycle", "OnResume")
        if(wasRunning){
            running = true
        }
    }

    override fun onPause() {
        super.onPause()
        Log.d("Lifecycle", "OnPause")
        wasRunning = running
        running = false
    }

}

